package com.example.demo.controller;

import com.example.demo.dto.NumDTO;
import com.example.demo.dto.ResponseDTO;
import com.example.demo.entity.BarCode;
import com.example.demo.entity.HistoryEntity;
import com.example.demo.service.HistoryService;
import com.example.demo.service.ReplaceService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@Slf4j
@Controller
@RequestMapping(value = "replace")
public class ReplaceController {

    @Resource
    private ReplaceService replaceService;

    @RequestMapping(value = "queryNew",method = RequestMethod.GET)
    @ResponseBody
    public ResponseDTO<BarCode> queryNew(String codeOld) {
        BarCode barCode = replaceService.queryNew(codeOld);
        if(barCode == null) {
            return ResponseDTO.error(-1,"未找到新码");
        }
        return ResponseDTO.ok(barCode);
    }

    @RequestMapping(value = "queryNum",method = RequestMethod.GET)
    @ResponseBody
    public ResponseDTO<NumDTO> queryNum(String oldCode) {
        return ResponseDTO.ok(replaceService.queryNum(oldCode));
    }

    /**
     * 考虑到损坏，扫码数量不做限制
     */
    @RequestMapping(value = "replace",method = RequestMethod.GET)
    @ResponseBody
    public ResponseDTO<BarCode> replace(String codeOld) {

        BarCode barCode = replaceService.queryNew(codeOld);
        if(barCode == null) {
            return ResponseDTO.error(-1,"未找到新码");
        }
        //打印并且打印数+1
        //不用考虑并发问题
        int scanNum = barCode.getScanNum() + 1;
        barCode.setScanNum(scanNum);
        replaceService.updateById(barCode);
        //记录详情
        replaceService.insertDetail(barCode.getCodeOld(),barCode.getCodeNew());

        return ResponseDTO.ok(barCode);
    }

    @RequestMapping(value = "randomPrint",method = RequestMethod.GET)
    @ResponseBody
    public ResponseDTO<List<BarCode>> randomPrint() {
        return ResponseDTO.ok(replaceService.randomPrint());
    }

    @PostMapping("upload")
    public void upload(@RequestParam("file") MultipartFile file) throws Exception {
        log.info("OriginalFilename:{}",file.getOriginalFilename());
        replaceService.importData(file.getInputStream(),file.getOriginalFilename());
    }


}
